﻿using DrCarDrive.DBService;
using DrCarDrive.Util;
using DrCarDrive.Wpf.WpfWindow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DrCarDrive.Wpf.WpfPage
{
    /// <summary>
    /// Interaction logic for AddVillageRecordPage.xaml
    /// </summary>


    public partial class AddVillageRecordPage : Page
    {
        private static AddVillageRecordPage instance;
        private PlaceService placeService;
        private MedicineService medicineService;
        public AddVillageRecordPage()
        {
            InitializeComponent();
            tbl_drive td = new tbl_drive();
            this.DataContext = td;
        }

        public static AddVillageRecordPage Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new AddVillageRecordPage();
                }

                return instance;
            }
        }

        private void btnArrivalSave_Click(object sender, RoutedEventArgs e)
        {
            if (validateArrival() == true)
            {
                tbl_places place = new tbl_places();
                place.ID = GUIDGenerator.placesKey();
                place.VILLAGE_NAME = txtArrivalVillage.Text;
                place.ARRIVAL_DATE = DateTime.ParseExact(dtpArrivalDateTime.Text, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
                place.ARRIVAL_ODOMETER = Double.Parse(txtArrivalOdoMeter.Text);
                place.STATUS = false;
                place.FKY_DRIVE = SessionData.drive.ID;
                place.FKY_VILLAGE = null;
                place.REMARK = "";
                placeService = new PlaceService();

                int status = placeService.save(place);
                if (status > 0)
                {
                    SessionData.place = place;
                    MSGWindow success = new MSGWindow("Health Center Added", Messages.SUCC_VILLAGE_ADD);
                    SetArrivalMode("Update");
                    txtDepartureOdometer.Text = place.ARRIVAL_ODOMETER.ToString();
                    success.ShowDialog();

                }
                else
                {
                    MSGWindow error = new MSGWindow("Error", Messages.ERR_VILLAGE_ADD);
                    error.ShowDialog();
                }
            }
            else
            {
                MSGWindow errorWindow = new MSGWindow(Messages.TTL_FILL_REQUIRED, Messages.MSG_FILL_REQUIRED_INFORMATION);
                errorWindow.ShowDialog();
            }
        }

        private Boolean validateArrival()
        {
            if (txtArrivalVillage.Text == "" || txtArrivalOdoMeter.Text == "" || dtpArrivalDateTime.Value == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private void SetArrivalMode(string mode)
        {
            if (mode == "Save")
            {
                btnArrivalSave.Visibility = System.Windows.Visibility.Visible;
                btnArrivalUpdate.Visibility = System.Windows.Visibility.Hidden;
                tbiMedicine.IsEnabled = false;
                tbiPatient.IsEnabled = false;
                tbiDeparture.IsEnabled = false;
            }
            else if (mode == "Update")
            {
                btnArrivalSave.Visibility = System.Windows.Visibility.Hidden;
                btnArrivalUpdate.Visibility = System.Windows.Visibility.Visible;
                tbiMedicine.IsEnabled = true;
                tbiPatient.IsEnabled = true;
                tbiDeparture.IsEnabled = true;
            }

        }

        private void btnArrivalUpdate_Click(object sender, RoutedEventArgs e)
        {
            if (validateArrival() == true)
            {
                tbl_places place = SessionData.place;
                place.VILLAGE_NAME = txtArrivalVillage.Text;
                place.ARRIVAL_DATE = DateTime.ParseExact(dtpArrivalDateTime.Text, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
                place.ARRIVAL_ODOMETER = Double.Parse(txtArrivalOdoMeter.Text);

                placeService = new PlaceService();
                int status = placeService.update(place);
                if (status > 0)
                {
                    MSGWindow success = new MSGWindow("Health Center Record", Messages.SUCC_VILLAGE_UPDATE);
                    success.ShowDialog();
                    txtDepartureOdometer.Text = place.ARRIVAL_ODOMETER.ToString();
                    SessionData.place = place;
                }
                else
                {
                    MSGWindow error = new MSGWindow("Error", Messages.ERR_VILLAGE_ADD);
                    error.ShowDialog();
                }
            }
            else
            {
                MSGWindow errorWindow = new MSGWindow(Messages.TTL_FILL_REQUIRED, Messages.MSG_FILL_REQUIRED_INFORMATION);
                errorWindow.ShowDialog();
            }
        }

        private void btnArrivalCancel_Click(object sender, RoutedEventArgs e)
        {
            if (btnArrivalUpdate.Visibility == System.Windows.Visibility.Visible)
            {
                txtArrivalVillage.Text = SessionData.place.VILLAGE_NAME;
                dtpArrivalDateTime.Value = SessionData.place.ARRIVAL_DATE;
                txtArrivalOdoMeter.Text = SessionData.place.ARRIVAL_ODOMETER.ToString();
            }
            else
            {
                txtArrivalVillage.Text = "";
                dtpArrivalDateTime.Text = "";
                txtArrivalOdoMeter.Text = "";
            }
        }

        private void btnPatientCancel_Click(object sender, RoutedEventArgs e)
        {
            if (btnPatientSave.Content == "Update")
            {
                txtNumPatients.Text = SessionData.place.NUMBER_PATIENT.ToString();
                txtNumDoctors.Text = SessionData.place.NUMBER_DOCTORS.ToString();
                txtNumParamedics.Text = SessionData.place.NUMBER_PARAMEDICS.ToString();
                txtPatientRemark.Text = SessionData.place.REMARK.ToString();
            }
            else
            {
                txtNumPatients.Text = "";
                txtNumDoctors.Text = "";
                txtNumParamedics.Text = "";
                txtPatientRemark.Text = "";
            }
        }

        private void btnPatientSave_Click(object sender, RoutedEventArgs e)
        {
            if (validatePatient() == true)
            {
                tbl_places place = SessionData.place;
                if (txtNumDoctors.Text != "")
                {
                    place.NUMBER_DOCTORS = Int32.Parse(txtNumDoctors.Text);
                }
                if (txtNumParamedics.Text != "")
                {
                    place.NUMBER_PARAMEDICS = Int32.Parse(txtNumParamedics.Text);
                }
                if (txtNumPatients.Text != "")
                {
                    place.NUMBER_PATIENT = Int32.Parse(txtNumPatients.Text);
                }
                place.REMARK = txtPatientRemark.Text;

                placeService = new PlaceService();
                int status = placeService.update(place);
                if (status > 0)
                {
                    MSGWindow success = new MSGWindow("Health Center Record Updated", Messages.SUCC_VILLAGE_UPDATE);
                    success.ShowDialog();
                    btnPatientSave.Content = "Update";
                    SessionData.place = place;
                }
                else
                {
                    MSGWindow error = new MSGWindow("Error", Messages.ERR_VILLAGE_UPDATE);
                    error.ShowDialog();
                }
            }
            else
            {
                MSGWindow errorWindow = new MSGWindow(Messages.TTL_FILL_REQUIRED, Messages.MSG_FILL_REQUIRED_INFORMATION);
                errorWindow.ShowDialog();
            }

        }

        private bool validatePatient()
        {
           if (txtNumPatients.Text == "")
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private void btnDepartureCancel_Click(object sender, RoutedEventArgs e)
        {
            dtpDepartureDateTime.Text = "";
            txtDepartureOdometer.Text = "";
        }

        private void btnDepartureSave_Click(object sender, RoutedEventArgs e)
        {
            ConfirmationWindow conf = new ConfirmationWindow(Messages.TTL_END_DRIVE, Messages.MSG_END_DRIVE_CONF);
            conf.ShowDialog();
            //if (ConfirmationWindow.) ;
            if (validateDeparture()==true)
            {
                SessionData.place.DEPARTURE_DATE = DateTime.ParseExact(dtpDepartureDateTime.Text, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);

                double odometer;
                Double.TryParse(txtDepartureOdometer.Text, out odometer);
                SessionData.place.DEPARTURE_ODOMETER = odometer;
                
                SessionData.place.STATUS = true;

                placeService = new PlaceService();
                int status = placeService.update(SessionData.place);
                if (status > 0)
                {
                    clearAll();
                    AddVillageRecordPage.destroy();
                    MainWindow.Instance.ContentFrame.Content = DashboardPage.Instance;
                    if (SessionData.place != null)
                    {
                        SessionData.totalPatients += SessionData.place.NUMBER_PATIENT;
                    }
                }
                else
                {
                    MSGWindow error = new MSGWindow("Error", Messages.ERR_VILLAGE_UPDATE);
                    error.ShowDialog();
                }
            }
            else
            {
                MSGWindow errorWindow = new MSGWindow(Messages.TTL_FILL_REQUIRED, Messages.MSG_FILL_REQUIRED_INFORMATION);
                errorWindow.ShowDialog();
            }
        }

        private bool validateDeparture()
        {
            if (dtpDepartureDateTime.Value == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private void clearAll()
        {
            txtArrivalVillage.Text = "";
            dtpArrivalDateTime.Text = "";
            txtArrivalOdoMeter.Text = "";
            txtNumPatients.Text = "";
            txtNumDoctors.Text = "";
            txtNumParamedics.Text = "";
            dtpDepartureDateTime.Text = "";
            txtDepartureOdometer.Text = "";
        }

        public static void destroy()
        {
            instance = null;
        }

        private void btnMedicineCancel_Click(object sender, RoutedEventArgs e)
        {
            clearMedicinePage();
        }

        private void clearMedicinePage()
        {
            cmbMedicine.SelectedIndex = -1;
            txtDosage.Text = "";
            txtMedicineRemark.Text = "";
            txtUnit.Text = "";
        }

        private void btnMedicineSave_Click(object sender, RoutedEventArgs e)
        {
            if (validateMedicine() == true)
            {
                tbl_issue_medicine medicine = new tbl_issue_medicine();
                medicine.ID = GUIDGenerator.medicineKey();
                medicine.DOSAGE = Double.Parse(txtDosage.Text);
                medicine.UNIT = txtUnit.Text;
                medicine.REMARK = txtMedicineRemark.Text;
                medicine.FKY_PLACE = SessionData.place.ID;
                medicine.FKY_MEDICINE = cmbMedicine.SelectedValue.ToString();

                medicineService = new MedicineService();
                //MessageBox.Show();
                int status = medicineService.save(medicine);
                if (status > 0)
                {
                    MSGWindow success = new MSGWindow("Medicine Record Added", Messages.SUCC_MEDICINE_ADD);
                    clearMedicinePage();
                }
            }
            else
            {
                MSGWindow errorWindow = new MSGWindow(Messages.TTL_FILL_REQUIRED, Messages.MSG_FILL_REQUIRED_INFORMATION);
                errorWindow.ShowDialog();
            }



        }

        private Boolean validateMedicine()
        {
            if (txtDosage.Text == "" || cmbMedicine.SelectedIndex == -1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private void cmbMedicine_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SelectMedicineTextBlock.Visibility = cmbMedicine.SelectedItem == null ? Visibility.Visible : Visibility.Hidden;
        }

        private void Page_Loaded_1(object sender, RoutedEventArgs e)
        {
            MedicineService medicineService = new MedicineService();
            List<tbl_drive_medicine> medicineList = medicineService.getMedicineList();

            cmbMedicine.ItemsSource = medicineList;
            cmbMedicine.DisplayMemberPath = "NAME";
            cmbMedicine.SelectedValuePath = "ID";

            tbl_places currentPlace = SessionData.place;
            if (currentPlace != null && currentPlace.STATUS == false)
            {
                loadCurrentPlaceRecord(currentPlace);
            }
        }

        private void loadCurrentPlaceRecord(tbl_places currentPlace)
        {
            txtArrivalVillage.Text = currentPlace.VILLAGE_NAME;
            txtArrivalOdoMeter.Text = currentPlace.ARRIVAL_ODOMETER.ToString();
            dtpArrivalDateTime.Text = currentPlace.ARRIVAL_DATE.ToString();
            txtNumDoctors.Text = currentPlace.NUMBER_DOCTORS.ToString();
            txtNumPatients.Text = currentPlace.NUMBER_PATIENT.ToString();
            txtNumParamedics.Text = currentPlace.NUMBER_PARAMEDICS.ToString();
            txtPatientRemark.Text = currentPlace.REMARK.ToString();
            SetArrivalMode("Update");
            btnPatientSave.Content = "Update";
        }


        private void txtArrivalOdoMeter_TextChanged(object sender, TextChangedEventArgs e)
        {
            txtArrivalOdoMeter.Text = LeaveOnlyNumbers(txtArrivalOdoMeter.Text);
        }

        private string LeaveOnlyNumbers(String inString)
        {
            String tmp = inString;
            foreach (char c in inString.ToCharArray())
            {
                if (!IsDigit(c))
                {
                    tmp = tmp.Replace(c.ToString(), "");
                }
            }
            return tmp;
        }

        public bool IsDigit(char c)
        {
            return (c >= '0' && c <= '9');
        }
        private void txtArrivalOdoMeter_KeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = !IsNumberKey(e.Key) && !IsActionKey(e.Key);
        }
        private bool IsNumberKey(Key inKey)
        {
            if (inKey < Key.D0 || inKey > Key.D9)
            {
                if (inKey < Key.NumPad0 || inKey > Key.NumPad9)
                {
                    return false;
                }
            }
            return true;
        }

        private bool IsActionKey(Key inKey)
        {
            return inKey == Key.Delete || inKey == Key.Back || inKey == Key.Tab || inKey == Key.Return || Keyboard.Modifiers.HasFlag(ModifierKeys.Alt);
        }



        private void txtNumPatients_KeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = !IsNumberKey(e.Key) && !IsActionKey(e.Key);
        }

        private void txtNumDoctors_KeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = !IsNumberKey(e.Key) && !IsActionKey(e.Key);
        }

        private void txtNumParamedics_KeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = !IsNumberKey(e.Key) && !IsActionKey(e.Key);
        }

        private void txtDepartureOdometer_KeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = !IsNumberKey(e.Key) && !IsActionKey(e.Key);
        }

        private void tbiDeparture_GotFocus(object sender, RoutedEventArgs e)
        {
            if (SessionData.place != null)
            {
                txtDepartureOdometer.Text = SessionData.place.ARRIVAL_ODOMETER.ToString();
            }
        }

        private void txtDosage_KeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = !IsNumberKey(e.Key) && !IsActionKey(e.Key);
        }
    }
}
